<?php


namespace App\Http\Controllers\Admin\Screen;


use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use App\Response\Response;
use Illuminate\Http\Request;

use function Clue\StreamFilter\fun;
use function foo\func;

class ScreenLog extends BaseController
{


    /**
     * @api {get} /screen/log 上公屏纪录
     * @apiVersion 0.1.0
     * @apiName 上公屏纪录
     * @apiGroup 上公屏
     * @apiParam {Int}                     page  （选填）
     * @apiParam {Int}                     page_size  （选填）
     * @apiParam {Int}                     user_id  （选填）
     * @apiParam {Int}                     room_id  （选填）
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "total": 2,
     * "current_page": 1,
     * "last_page": 1,
     * "list": [
     * {
     * "id": 6660,
     * "room_id": 35,
     * "user_id": 547177,
     * "join_type": 1,//活动模式 1表示答题 2表示送礼
     * "join_exp_limit": 1,
     * "join_rule": null,
     * "winner_type": 1,//奖品类型 1表示礼物奖励 2表示自定义奖励
     * "winner_gift_id": 1,
     * "winner_gift_name": "",
     * "winner_num": 1,//奖品数量
     * "end_at": "0000-00-00 00:00:00",
     * "stop_at": "0000-00-00 00:00:00",
     * "status": 1,
     * "created_at": "2021-08-20 14:31:37",//活动时间
     * "updated_at": "2021-08-20 14:53:42",
     * "user_room": {
     * "id": 35,
     *       "room_id": 2351964//房间id
     * "room_name": "FM自己走"//房间名称
     * },
     * "user_data": {
     * "user_id": 547177,
     * "user_code": 4515843//用户id
     * "nickname": "111佳人有约"//发起用户
     * },
     *   "gift": {
     * "id": 691,
     * "name": "物理"//奖品内容 奖品名称
     * }
     * },
     * {
     * "id": 6661,
     * "room_id": 35,
     * "user_id": 547177,
     * "join_type": 1,
     * "join_exp_limit": 0,
     * "join_rule": null,
     * "winner_type": 1,
     * "winner_gift_id": 1,
     * "winner_gift_name": "",//
     * "winner_num": 1,
     * "end_at": "0000-00-00 00:00:00",
     * "stop_at": "0000-00-00 00:00:00",
     * "status": 1,
     * "created_at": "2021-08-20 14:32:52",
     * "updated_at": "2021-08-20 14:53:46",
     * "user_room": {
     * "id": 35,
     * "room_name": "FM自己走"
     * },
     * "user_data": {
     * "user_id": 547177,
     *      "user_code": 4515843//用户id
     * "nickname": "111佳人有约"//发起用户
     * }
     *  "gift": {
     * "id": 691,
     * "name": "物理"//奖品内容 奖品名称
     * }
     * }
     * ]
     * }
     * }
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function logList(Request $request)
    {
        $data = $request->only(['user_id', 'room_id', 'page', 'page_size']);
        $v = app('validator')->make($request->all(),
            [
                'page'      => 'integer|min:1',
                'page_size' => 'integer|min:1',
                'user_id'   => 'integer|min:1',
                'room_id'   => 'integer|min:1',
            ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }
        $data['page'] = $data['page'] ?? 1;
        $data['page_size'] = $data['page_size'] ?? 5;
        $model = app('model_screen_activity')
            ->with([
                'userRoom'    => function ($query) {
                    $query->select(['id', 'room_name', 'room_id']);
                }, 'userData' => function ($query) {
                    $query->select(['user_id', 'nickname', 'user_code']);
                }, 'gift'     => function ($query) {
                    $query->select(['id', 'name']);
                },
            ])->orderBy('id', 'desc');
        if (isset($data['user_id'])) {
            $model = $model->wherehas('userData', function ($query) use ($data) {
                $query->where('user_code', $data['user_id']);
            });
        }
        if (isset($data['room_id'])) {
            $model = $model->wherehas('userRoom', function ($query) use ($data) {
                $query->where('room_id', $data['room_id']);
            });
        }
        $list = $model->paginate($data['page_size'], ['*'], '', $data['page']);

        //        if (empty($where)) {
        //            $list = $model->paginate($data['page_size'], ['*'], '', $data['page']);
        //        } else {
        //            $list = $model->wherehas('userData',function ($query){
        //                $query->where()
        //            })->paginate($data['page_size'], ['*'], '', $data['page']);
        //        }
        //        if (empty($list)) {
        //            throw new BasicException(10001, '没有数据');
        //        }
        $list = $list->toArray();
        foreach ($list['data'] as $k => &$value) {
            if ($value['winner_type'] == 2) {
                $list['data'][$k]['gift'] = [
                    'id'   => 0,
                    'name' => $value['winner_gift_name'],
                ];
            }
        }

        $result = [
            'total'        => $list['total'] ?? 0,
            'current_page' => $list['current_page'] ?? 1,
            'last_page'    => $list['last_page'] ?? 1,
            'list'         => $list['data'],
        ];

        return Response::sendData($result);
    }

    /**
     * @api {get} /screen/log/winner_log 中奖纪录
     * @apiVersion 0.1.0
     * @apiName 中奖纪录
     * @apiGroup 上公屏
     * @apiParam {Int}                     page  （选填）
     * @apiParam {Int}                     page_size  （选填）
     * @apiParam {Int}                     user_id  （选填）
     * @apiParam {Int}                     room_id  （选填）
     * @apiParam {Int}                     activity_id 大屏活动id （选填）
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "total": 1,
     * "current_page": 1,
     * "last_page": 1,
     * "list": [
     * {
     * "id": 6660,
     * "activity_id": 6664,
     * "user_id": 643537,
     * "record_id": 1,
     * "gift_id": 2,
     * "gift_name": "1",
     * "winner_num": 1,
     * "send_status": 1,
     * "created_at": "2021-08-20 15:55:34",//中奖时间
     * "updated_at": "2021-08-20 16:05:20",
     * "user_data": {
     * "user_id": 643537,
     * "nickname": "主绢子2338698"//用户昵称
     *   "user_code": 9024746//用户id
     * },
     * "activity": {
     * "id": 6664,
     * "user_id":12//发奖用户id
     * "room_id": 3375,
     * "winner_gift_name": "自定义礼物名称"
     *  "user_data": {
     * "user_id": 643537,
     * "nickname": "主绢子2338698",
     * "user_code": 2338698//发奖用户id
     * }
     * }
     *  "user_room": {
     * "id": 3375,
     * "room_name": "韩硕的房间",
     * "room_id": 7337525//房间id
     * },
     *  "gift": {
     * "id": 691,
     * "name": "物理"//奖品内容
     * }
     * }
     * ]
     * }
     * }
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function winPrizeLog(Request $request)
    {
        $data = $request->only(['activity_id', 'user_id', 'room_id', 'page', 'page_size']);
        $v = app('validator')->make($request->all(),
            [
                'activity_id' => 'integer|min:1',
                'user_id'     => 'integer|min:1',
                'room_id'     => 'integer|min:1',
                'page'        => 'integer|min:1',
                'page_size'   => 'integer|min:1',
            ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }
        $data['page'] = $data['page'] ?? 1;
        $data['page_size'] = $data['page_size'] ?? 5;
        $where = [];

        if (isset($data['activity_id'])) {
            $where[] = ['activity_id', '=', $data['activity_id']];
        }

        $roomFun = function ($query) {
            $query->select(['id', 'room_name', 'room_id']);
        };
        $useFun = function ($query) {
            $query->select(['user_id', 'nickname', 'user_code']);
        };
        $activityFun = function ($query) {
            $query->select(['id', 'room_id', 'user_id', 'winner_gift_name'])->with([
                'userData' => function ($que) {
                    $que->select(['user_id', 'nickname', 'user_code']);
                },
            ]);
        };
        $giftFun = function ($query) {
            $query->select(['id', 'name']);
        };
        $model = app('model_screen_winner')
            ->with([
                'userRoom' => $roomFun, 'userData' => $useFun, 'activity' => $activityFun, 'gift' => $giftFun,
            ])->orderBy('id', 'desc');
        $model = !empty($where) ? $model->where($where) : $model;
        if (isset($data['user_id'])) {
            $model = $model->wherehas('userData', function ($query) use ($data) {
                $query->where('user_code', $data['user_id']);
            });
        }
        if (isset($data['room_id'])) {
            $model = $model->wherehas('userRoom', function ($query) use ($data) {
                $query->where('room_id', $data['room_id']);
            });
        }
        $list = $model->paginate($data['page_size'], ['*'], '', $data['page']);
        if (empty($list)) {
            throw new BasicException(10001, '没有数据');
        }
        $list = $list->toArray();
        foreach ($list['data'] as $k => &$value) {
            if ($value['winner_type'] == 2) {
                $list['data'][$k]['gift'] = [
                    'id'   => 0,
                    'name' => $value['gift_name'],
                ];
            }
        }
        $result = [
            'total'        => $list['total'] ?? 0,
            'current_page' => $list['current_page'] ?? 1,
            'last_page'    => $list['last_page'] ?? 1,
            'list'         => $list['data'],
        ];

        return Response::sendData($result);
    }

    //礼物配置列表

    /**
     * @api {get} /screen/gift 礼物配置列表
     * @apiVersion 0.1.0
     * @apiName 礼物配置列表
     * @apiGroup 上公屏
     * @apiParam {Int}                     page  （选填）
     * @apiParam {Int}                     page_size  （选填）
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "total": 2,
     * "current_page": 1,
     * "last_page": 1,
     * "list": [
     * {
     * "id": 6661,
     * "gift_id": 1,
     * "gift_img": "",//礼物图片
     * "status": 1,//状态 1启用 2禁用
     * "created_at": "2021-08-20 14:07:18",
     * "updated_at": "2021-08-20 16:30:10",
     * "gift": {
     * "id": 1,
     * "name": "萤火之森"//礼物名称
     * "price":123,//价格
     * }
     * },
     * {
     * "id": 6660,
     * "gift_id": 1,
     * "gift_img": "",
     * "status": 1,
     * "created_at": "2021-08-20 14:07:14",
     * "updated_at": "2021-08-20 14:07:19",
     * "gift": {
     * "id": 1,
     * "name": "萤火之森"
     * "price":123,
     * }
     * }
     * ]
     * }
     * }
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function giftConfigList(Request $request)
    {
        $data = $request->only(['page', 'page_size']);
        $v = app('validator')->make($request->all(),
            [
                'page'      => 'integer|min:1',
                'page_size' => 'integer|min:1',
            ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }
        $data['page'] = $data['page'] ?? 1;
        $data['page_size'] = $data['page_size'] ?? 5;
        $list = app('model_screen_gift')
            ->with([
                'gift' => function ($query) {
                    $query->select(['id', 'name', 'price']);
                },
            ])
            ->where('is_del', 0)
            ->orderBy('created_at', 'desc')
            ->paginate($data['page_size'], ['*'], '', $data['page']);
        $list = $list->toArray();
        $result = [
            'total'        => $list['total'] ?? 0,
            'current_page' => $list['current_page'] ?? 1,
            'last_page'    => $list['last_page'] ?? 1,
            'list'         => $list['data'],
        ];

        return Response::sendData($result);
    }

    //添加上公屏礼物

    /**
     * @api {post} /screen/gift 添加礼物配置
     * @apiVersion 0.1.0
     * @apiName 添加礼物配置
     * @apiGroup 上公屏
     * @apiParam {Int}                     gift_id  （必填）
     * @apiParam {String}                     gift_img 礼物图片地址 （必填）
     * @apiParam {Int}                     status 状态 1启用 2禁用 （必填）
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": true
     * }
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function addScreenGift(Request $request)
    {
        $data = $request->only(['gift_id', 'gift_img', 'status']);
        $v = app('validator')->make($request->all(),
            [
                'gift_id'  => 'required|integer|min:1',
                'gift_img' => 'required|string|max:250',
                'status'   => 'required|integer|in:1,2',
            ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }
        $isHaveGift = app('model_gift')->where('id', $data['gift_id'])->where('sold', 1)->first();
        if (empty($isHaveGift)) {
            throw new BasicException(10001, '没有该礼物');
        }
        $res = app('model_screen_gift')->insert($data);
        if ($res) {
            return Response::sendData(true);
        } else {
            throw  new BasicException(10001, '插入失败');
        }
    }

    //修改上公屏礼物

    /**
     * @api {put} /screen/gift 修改上公屏礼物
     * @apiVersion 0.1.0
     * @apiName 修改上公屏礼物
     * @apiGroup 上公屏
     * @apiParam {Int}                     id  （必填）
     * @apiParam {Int}                     gift_id  （必填）
     * @apiParam {String}                     gift_img 礼物图片地址 （必填）
     * @apiParam {Int}                     status 状态 1启用 2禁用 （必填）
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": true
     * }
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function editScreenGift(Request $request)
    {
        $data = $request->only(['id', 'gift_id', 'gift_img', 'status']);
        $v = app('validator')->make($request->all(),
            [
                'id'       => 'required|integer|min:1',
                'gift_id'  => 'required|integer|min:1',
                'gift_img' => 'required|string|max:250',
                'status'   => 'required|integer|in:1,2',
            ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }
        $isHaveGift = app('model_gift')->where('id', $data['gift_id'])->where('sold', 1)->first();
        if (empty($isHaveGift)) {
            throw new BasicException(10001, '没有该礼物');
        }

        $res = app('model_screen_gift')->where('is_del', 0)->where('id', $data['id'])->update($data);

        if ($res) {
            return Response::sendData(true);
        } else {
            throw  new BasicException(10001, '修改失败');
        }
    }

    //状态切换

    /**
     * @api {put} /screen/gift/status 状态切换
     * @apiVersion 0.1.0
     * @apiName 状态切换
     * @apiGroup 上公屏
     * @apiParam {Int}                     id  （必填）
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": true
     * }
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function changeStatus(Request $request)
    {
        $data = $request->only(['id']);
        $v = app('validator')->make($request->all(),
            [
                'id' => 'required|integer|min:1',
            ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }
        $model = app('model_screen_gift');
        $isHaveGift = $model->where('is_del', 0)->where('id', $data['id'])->first();
        if (empty($isHaveGift)) {
            throw new BasicException(10001, '没有该礼物配置');
        }
        $status = $isHaveGift['status'] == 1 ? 2 : 1;
        $res = $isHaveGift->update(['status' => $status]);
        if ($res) {
            return Response::sendData(true);
        } else {
            throw  new BasicException(10001, '状态修改失败');
        }
    }
    //礼物下拉列表框

    /**
     * @api {get} /screen/gift/pro 礼物下拉列表框
     * @apiVersion 0.1.0
     * @apiName 礼物下拉列表框
     * @apiGroup 上公屏
     * @apiParam {Int}                     page  （选填）
     * @apiParam {Int}                     page_size  （选填）
     * @apiParam {Int}                     name 礼物名称 （选填）
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "total": 205,
     * "current_page": 1,
     * "last_page": 103,
     * "list": [
     * {
     * "id": 231,
     * "name": "纸飞机",
     * "picture": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5f06f2a462e1e.png",
     * "price": 1314,//价格
     * "special": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5f06f2a78ec74.png",
     * "sort": 1314,
     * "type": 2,
     * "sold": 1,
     * "cardiac": 1314,
     * "frame_id": 28
     * },
     * {
     * "id": 349,
     * "name": "龙吟鹤唳",
     * "picture": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5fad4a30215e8.png",
     * "price": 999999,
     * "special": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5fad4a33eb507.svga",
     * "sort": 999,
     * "type": 1,
     * "sold": 1,
     * "cardiac": 999999,
     * "frame_id": 2
     * }
     * ]
     * }
     * }
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function giftList(Request $request)
    {
        $data = $request->only(['page', 'page_size', 'name']);
        $data['page'] = $data['page'] ?? 1;
        $data['page_size'] = $data['page_size'] ?? 10;
        $data['name'] = $data['name'] ?? '';
        $where = [
            ['name', 'like', '%' . $data['name'] . '%'],
            ['sold', '=', 1],
        ];
        $list = app('model_gift')
            ->where($where)
            ->orderBy('sort', 'desc')
            ->paginate($data['page_size'], ['*'], '', $data['page'])
            ->toArray();
        $result = [
            'total'        => $list['total'] ?? 0,
            'current_page' => $list['current_page'] ?? 1,
            'last_page'    => $list['last_page'] ?? 1,
            'list'         => $list['data'],
        ];

        return Response::sendData($result);
    }

    //删除上公屏礼物

    /**
     * @api {get} /screen/gift 删除上公屏礼物
     * @apiVersion 0.1.0
     * @apiName 删除上公屏
     * @apiGroup 上公屏
     * @apiParam {Int}                     id  （选填）

     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * }
     * }
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function del(Request $request)
    {
        $data = $request->only(['id']);
        $v = app('validator')->make($request->all(),
            [
                'id' => 'required|integer|min:1',
            ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }
        $Res = app('model_screen_gift')
            ->where('id', $data['id'])
            ->update(['is_del' => 1, 'status' => 2]);
        if ($Res) {
            return Response::sendData('删除成功');
        } else {
            throw  new BasicException(10001, '删除失败');
        }
    }

}